<template>
  <div class="login" v-loading="loading">
    <el-card>
      <el-form :model="loginForm" :rules="rules" ref="loginForm">
        <h3>智能停车场管理系统</h3>
        <span style="letter-spacing: 20px;text-shadow: -4px -4px 5px #aaa;font-variant: all-small-caps;word-spacing: 3px;">welcome </span>
        <el-form-item style="margin-top: 40px" prop="account">
          <el-input size="small" placeholder="用户名" v-model="loginForm.account"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="small" placeholder="密码" type="password" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item >
          <el-button type="success" size="small" style="margin-top: 10px" @click="login(loginForm)">登&nbsp;&nbsp;&nbsp;&nbsp;录</el-button>
          <el-button type="info" size="small" style="margin-top: 10px" @click="openRegister">注&nbsp;&nbsp;&nbsp;&nbsp;册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog
            title="注册"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose">
      <el-form :model="registerForm" status-icon :rules="rules2" :ref="registerForm" label-width="100px">
          <el-form-item label="账户名" prop="account">
            <el-input type="text" v-model="registerForm.account" autocomplete="off"></el-input>
          </el-form-item>
        <el-form-item label="真实姓名" prop="username">
          <el-input v-model="registerForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="registerForm.password" autocomplete="off"></el-input>
          </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" v-model="registerForm.checkPass" autocomplete="off"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button @click="resetForm(registerForm)">重置</el-button>
         <el-button type="success" @click="register(registerForm)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import Message from '../components/messages/index.js'
  import {Loading} from 'element-ui'
  export default {
      data(){
          const validateUsername = (rule, value, callback)=>{
               value = value.split(" ").join("");
               if (value === '') {
                   callback(new Error('请输入有效值'));
               }else if (value.length<3) {
                   callback(new Error('字段名太短'));
               }else {
                   callback();
               }
           };
          const validatePass = (rule, value, callback) => {
              value = value.split(" ").join("");
              if (value === '') {
                  callback(new Error('请输入密码'));
              }else{
                  callback();
              }
          };
          const validatePass2 = (rule, value, callback) => {
              value = value.split(" ").join("");
              if (value === '') {
                  callback(new Error('请再次输入密码'));
              } else if (value !== this.registerForm.password) {
                  callback(new Error('两次输入密码不一致!'));
              } else {
                  callback();
              }
          };
          return{
              socketData:{},
              loading:false,
              loginForm:{
                  account:"",
                  password:""
              },
              rules:{
                account:[
                    { required: true, message: '请输入账户名', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ]
              },
              rules2:{
                  password: [
                      { validator: validatePass, trigger: 'blur' }
                  ],
                  checkPass: [
                      { validator: validatePass2, trigger: 'blur' }
                  ],
                  username: [
                      { validator: validateUsername, trigger: 'blur'}
                  ],
                  account: [
                      { validator: validateUsername, trigger: 'blur'}
                  ]
              },
              dialogVisible:false,
              registerForm:{
                  account:"",
                  password:"",
                  checkPass:"",
                  username:""
              },
              menuMap:{},
              loadingInstance:'',
              loadingOptions:{
                  lock:true,
                  text:'正在登陆中，请耐心等候...',
                  spinner: 'el-icon-loading',
                  background:'rgba(0,0,0,0.8)'
              },
          }
      },
      methods:{
          login(data){
            let self = this;
            if (data.account===""||data.password===""){
                self.$message.warning("用户名或密码不能为空！")
            }else {
                self.loadingInstance = Loading.service(self.loadingOptions);
                self.$http.post("/user/login",self.loginForm).then(res=>{
                    if (res.status===200) {
                        let user = res.data;
                        localStorage.setItem("user",JSON.stringify(user));
                        self.$http.get("/user/all").then(res=>{
                            if (res.status === 200){
                                let userList = res.data;
                                let userListData = [];
                                userList.forEach(user => {
                                    userListData.push({"id":user.id,"userName":user.userName})
                                });
                                localStorage.setItem("users",JSON.stringify(userListData));
                            }
                        }).catch(()=> Message.warning("用户列表获取失败!"));
                        self.$http.get("/role/all").then(res => {
                            if (res.status === 200){
                                let roleList = res.data;
                                localStorage.setItem("roles",JSON.stringify(roleList));
                            }
                        }).catch(() => Message.warning("角色列表获取失败"));
                        self.$http.get("/payRules/all").then(res => {
                          if (res.status === 200){
                            let ruleList = res.data;
                            localStorage.setItem("rules",JSON.stringify(ruleList));
                          }
                        }).catch(()=> Message.warning("付费规则缓存失败"));
                        self.$http.get("/coder/all").then(res => {
                            if (res.status === 200){
                                let coderList = res.data;
                                localStorage.setItem("coders",JSON.stringify(coderList));
                            }
                        }).catch(() => Message.warning("码表列表获取失败"));
                        self.$http.get("/resource/getMenuByUserId",{params:{"userId":user.id,"typeId":0}}).then(res=>{
                            if (res.status===200){
                                console.info(res.data);
                                localStorage.setItem("menu",JSON.stringify(res.data));
                                self.$router.push("/home");
                                self.$ws.initWebSocket(function (socket) {
                                    self.$store.commit('setSocket',socket);
                                    socket.onmessage = function (response) {
                                        if (typeof response.data === 'string'){
                                            console.log("客户端接收到的消息:",response.data);
                                            self.socketData = JSON.parse(response.data);
                                            console.log(self.socketData);
                                            Message.notification(self.socketData.msg,self.socketData.title,self.socketData.type==null?"success":self.socketData.type);
                                        }
                                    }
                                });
                            }

                        });
                        self.loadingInstance.close();
                    }
                }).catch(()=>{
                    Message.error("访问出错");
                    self.loadingInstance.close();
                });
                self.loadingInstance.close();

            }
          },
          openRegister(){
            this.dialogVisible = true;
          },
          register(registerForm){
              this.$refs[registerForm].validate((valid) => {
                  if (valid) {
                      this.$http.post("/user/add",registerForm).then(res=>{
                          if (res.status===200){
                              Message.success("注册成功");
                              this.dialogVisible=false;
                              this.$router.push("/login")
                          }
                      })
                  } else {
                      console.log('error submit!!');
                      return false;
                  }
              });
          },
          handleClose(){
            this.dialogVisible = false;
          },
          resetForm(registerForm) {
              this.$refs[registerForm].resetFields();
          },

      }
  }
</script>

<style lang="less">
  .login{
    display: flex;
    justify-content: center;
    text-align: center;
    align-items: center;
    width:100%;
    height: calc(~'100vh');
    background-color: #7FA1BE;
    .el-card{
      height: 340px;
      width: 400px;
      h3{
        padding-top: 40px;
        padding-bottom: 10px;
        letter-spacing: 10px;
        text-shadow: 0 12px 7px #c8e494;
      }
      .el-form-item{
        padding: 0 28px;
        .el-input__inner{
          text-align: center!important;
        }
      }
    }

  }

</style>

